<template>
  <div ref="refGroupContent" class="group-content">
    <div v-if="groupHeight > 42" class="btn-group">
      <a-button v-if="expendFlag" size="small" @click="toggle(false)">收起</a-button>
      <a-button v-else size="small" @click="toggle(true)">展开</a-button>
      <slot name="more"></slot>
    </div>
    <div ref="refGroupBox" class="wj-radio-group" style="height: auto">
      <slot></slot>
    </div>
  </div>
</template>
<script setup lang="ts">
import { computed, provide, ref, onUpdated } from 'vue'
const emits = defineEmits(['update:select', 'change'])

const props = defineProps<{
  type: 'radio' | 'multiple'
  select?: string | number | (string | number)[] | undefined
}>()
const radioGroupModelValue = computed(() => props.select)
const groupHeight = ref(0)
const refGroupContent = ref()
const refGroupBox = ref()
onUpdated(() => {
  groupHeight.value = refGroupBox.value.offsetHeight
})

const expendFlag = ref(true)
const toggle = (flag) => {
  expendFlag.value = flag
  if (flag) {
    refGroupContent.value.style.height = 'auto'
  } else {
    refGroupContent.value.style.height = 42 + 'px'
  }
}
const updateRadioGroupModelValue = (e) => {
  if (props.type === 'radio') {
    emits('update:select', e)
    emits('change', e)
  } else {
    let selectValue: (string | number)[] | undefined = (props.select as (string | number)[]) ?? []
    // selectValue = e ?? []

    const index = selectValue?.findIndex((item) => item === e)
    if (index > -1) {
      if (selectValue.length > 1) {
        selectValue.splice(index, 1)
      }
    } else if (!e) {
      selectValue = undefined
    } else {
      selectValue.push(e)
    }
    emits('update:select', selectValue)
    emits('change', selectValue)
  }
}
provide('radioGroupModelValue', { type: props.type, radioGroupModelValue, updateRadioGroupModelValue })
</script>
<style lang="less" scoped>
.group-content {
  overflow: hidden;

  .btn-group {
    width: 150px;
    float: right;
    margin-top: 10px;
  }
  .wj-radio-group {
    display: flex;
    flex-wrap: wrap;
    margin-right: 60px;
    align-items: center;
  }
}
</style>
